<!--
 * @Author: daidai
 * @Date: 2022-03-01 11:17:39
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-09-29 15:50:18
 * @FilePath: \web-pc\src\pages\big-screen\view\indexs\center-map.vue
-->
<template>
  <div class="centermap">
    <div class="maptitle">
      <div class="zuo"></div>
      <span class="titletext">{{ maptitle }}</span>
      <div class="you"></div>
    </div>
    <div class="mapwrap">
      <dv-border-box-13 :color="['#058b96']">
        <div class="quanguo" @click="getData(mapData.per)" v-if="code !== 'china'">
          {{ mapData.name }}
        </div>

        <Echart id="CenterMap" :options="options" ref="CenterMap" />
      </dv-border-box-13>
    </div>
  </div>
</template>

<script>
import xzqCode from "../../utils/map/xzqCode";
import { currentGET } from "api/modules";
import * as echarts from "echarts";
import { GETNOBASE } from "api";
import * as API from '@/api'
export default {
  data() {
    return {
      maptitle: "设备分布图",
      mapJSON: null,
      mapData: {},
      options: {},
      code: "china", //china 代表中国 其他地市是行政编码
      echartBindClick: false,
      isSouthChinaSea: false, //是否要展示南海群岛  修改此值请刷新页面
    };
  },
  created() { },

  mounted() {
    this.getData("china");
  },
  methods: {
    // http://datav.aliyun.com/portal/school/atlas/area_selector 省市区json数据
    async getData(name = "china") {
    const res = await API.POST('/admin/screen/map')
     if (res.code === 1) {
      this.mapJSON = res.data
    }
    
      // if(name === 'china'){
      //   this.mapData = {
      //     dataList: [
      //       {
      //         name: '广东省',
      //         value: 3244
      //       },
      //       {
      //         name: '江西省',
      //         value: 324
      //       }
      //     ],
      //     regionCode: "china",
      //     name: '中国'

      //   }
      // } else if (name === '360000') {
      //    this.mapData = {
      //     dataList: [
      //       {
      //         name: '新余市',
      //         value: 233
      //       }
      //     ],
      //     regionCode: "360000",
      //     name: '江西省',
      //     per: 'china'
      //   }
      // } else if(name === '440000') {
      //   this.mapData = {
      //     dataList: [
      //       {
      //         name: '深圳市',
      //         value: 23342
      //       },
      //        {
      //         name: '佛山市',
      //         value: 233
      //       },
      //        {
      //         name: '珠海市',
      //         value: 233
      //       },
      //       {
      //         name: '惠州市',
      //         value: 233
      //       }
      //     ],
      //     regionCode: "440000",
      //     per: 'china',
      //     name: '广东省'
      //   }
      // } else if (name === '440300') {
      //   this.mapData = {
      //     dataList: [
      //       {
      //         name: '宝安区',
      //         value: 23342
      //       },
      //       {
      //         name: '龙华区',
      //         value: 233
      //       },
      //       {
      //         name: '坪山区',
      //         value: 233
      //       },
      //       {
      //         name: '光明区',
      //         value: 233
      //       }
      //     ],
      //     regionCode: "440300",
      //      name: '深圳市',
      //      per: '440000'
      //   }
      // }
      if(name === 'china') {
        this.mapData = this.rewindData(this.mapJSON)
      } else if (name === '360000') {
        this.mapData = this.rewindData(this.findDataByCode('360000').sub, '江西省', '360000')
      } else if(name === '440000') {
        this.mapData = this.rewindData(this.findDataByCode('440000').sub, '广东省', '440000')
      } else if(name === '440300') {
        this.mapData = this.rewindData(this.findDataByCode('440300').sub, '深圳市', '440300', '440000')
      } else if(name === '440100'){
        this.mapData = this.rewindData(this.findDataByCode('440100').sub, '广州市', '440100', '440000')
      } else if(name === '441900'){
        this.mapData = this.rewindData(this.findDataByCode('441900').sub, '东莞市', '441900', '440000')
      } else if(name === '440600'){
        this.mapData = this.rewindData(this.findDataByCode('440600').sub, '佛山市', '440600', '440000')
      } else if(name === '440400'){
        this.mapData = this.rewindData(this.findDataByCode('440400').sub, '珠海市', '440400', '440000')
      } else if(name === '441300'){
        this.mapData = this.rewindData(this.findDataByCode('441300').sub, '惠州市', '441300', '440000')
      }
      this.getGeojson(this.mapData.regionCode, this.mapData.dataList);
      this.mapclick();
    },
    /**
     * @description: 获取geojson
     * @param {*} name china 表示中国 其他省份行政区编码
     * @param {*} mydata 接口返回列表数据
     * @return {*}
     */
    async getGeojson(name, mydata) {
      this.code = name;
      //如果要展示南海群岛并且展示的是中国的话
      let geoname = name
      if (this.isSouthChinaSea && name == "china") {
        geoname = "chinaNanhai";
      }
      //如果有注册地图的话就不用再注册 了
      let mapjson = echarts.getMap(name);
      if (mapjson) {
        mapjson = mapjson.geoJSON;
      } else {
        let path = ''
        if (process.env.NODE_ENV === 'development') {
          path = `./map-geojson/${geoname}.json`
        } else {
          path = `/assets/admin/screen/map-geojson/${geoname}.json`
        }
        mapjson = await GETNOBASE(path).then((res) => {
          return res;
        });
        echarts.registerMap(name, mapjson);
      }
      let cityCenter = {};
      let arr = mapjson.features;
      //根据geojson获取省份中心点
      arr.map((item) => {
        cityCenter[item.properties.name] =
          item.properties.centroid || item.properties.center;
      });
      let newData = [];
      mydata.map((item) => {
        if (cityCenter[item.name]) {
          newData.push({
            name: item.name,
            value: cityCenter[item.name].concat(item.value),
          });
        }
      });
      this.init(name, mydata, newData);
    },
    init(name, data, data2) {
      let top = 45;
      let zoom = 1.05;
      let option = {
        backgroundColor: "rgba(0,0,0,0)",

        geo: {
          map: name,
          roam: false,
          selectedMode: false, //是否允许选中多个区域
          zoom: zoom,
          top: top,
          // aspectScale: 0.78,
          show: false
        },
        series: [
          {
            name: "MAP",
            type: "map",
            map: name,
            // aspectScale: 0.78,
            data: data,
            // data: [1,100],
            selectedMode: false, //是否允许选中多个区域
            zoom: zoom,
            geoIndex: 10,
            top: top,
            tooltip: {
              show: true,
              formatter: function (params) {
                if (params.data) {
                  return params.name + "：" + params.data["value"];
                } else {
                  return params.name;
                }
              },
              backgroundColor: "rgba(0,0,0,.6)",
              borderColor: "rgba(147, 235, 248, .8)",
              textStyle: {
                color: "#FFF",
              },
            },
            label: {
              show: false,
              color: "#000",
              // position: [-10, 0],
              formatter: function (val) {
                if (val.data !== undefined) {
                  return val.name.slice(0, 2);
                } else {
                  return "";
                }
              },
              rich: {},
            },
            emphasis: {
              label: {
                show: false,
              },
              itemStyle: {
                areaColor: "#389BB7",
                borderWidth: 1,
              },
            },
            itemStyle: {
              borderColor: "rgba(147, 235, 248, .8)",
              borderWidth: 1,
              areaColor: {
                type: "radial",
                x: 0.5,
                y: 0.5,
                r: 0.8,
                colorStops: [
                  {
                    offset: 0,
                    color: "rgba(147, 235, 248, 0)", // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: "rgba(147, 235, 248, .2)", // 100% 处的颜色
                  },
                ],
                globalCoord: false, // 缺为 false
              },
              shadowColor: "rgba(128, 217, 248, .3)",
              shadowOffsetX: -2,
              shadowOffsetY: 2,
              shadowBlur: 10,
            }
          },
          {
            data: data2,
            type: "effectScatter",
            coordinateSystem: "geo",
            symbolSize: function (val) {
              return 4;
              // return val[2] / 50;
            },
            legendHoverLink: true,
            showEffectOn: "render",
            rippleEffect: {
              // period: 4,
              scale: 6,
              color: "rgba(255,255,255, 1)",
              brushType: "fill",
            },
            tooltip: {
              show: true,
              formatter: function (params) {
                if (params.data) {
                  return params.name + "：" + params.data["value"][2];
                } else {
                  return params.name;
                }
              },
              backgroundColor: "rgba(0,0,0,.6)",
              borderColor: "rgba(147, 235, 248, .8)",
              textStyle: {
                color: "#FFF",
              },
              itemStyle: {
                normal: {
                  color: '#F06C00'
                }
              }
            },
            label: {
              formatter: (param) => {
                return param.name.slice(0, 2) + ' ' + param.value[2] + '台';
              },

              fontSize: 16,
              offset: [0, 2],
              position: "bottom",
              textBorderColor: "#fff",
              textShadowColor: "#000",
              textShadowBlur: 10,
              textBorderWidth: 0,
              color: "#FFF",
              show: true,
            },
            // colorBy: "data",
            itemStyle: {
              color: "rgba(255,255,255,1)",
              borderColor: "rgba(2255,255,255,2)",
              borderWidth: 10,
              shadowColor: "red",
              shadowBlur: 10,
              shadowOffsetX: -3,
              shadowOffsetY: -2
            },
          },

        ],
        //动画效果
        // animationDuration: 1000,
        // animationEasing: 'linear',
        // animationDurationUpdate: 1000
      };
      this.options = option;
    },
    message(text) {
      this.$Message({
        text: text,
        type: "warning",
      });
    },
    mapclick() {
      if (this.echartBindClick) return;
      //单击切换到级地图，当mapCode有值,说明可以切换到下级地图
      this.$refs.CenterMap.chart.on("click", (params) => {
        console.log(params)
        let xzqData = xzqCode[params.name];
        if (xzqData) {
          this.getData(xzqData.adcode);
        } else {
          this.message("暂无下级地市!");
        }
      });
      this.echartBindClick = true;
    },
    findDataByCode(code, jsonData = this.mapJSON) {
      // 从顶层数据开始递归搜索
      function search(codeToFind, data) {
        // 检查当前层级是否存在code匹配

        if (data.hasOwnProperty(codeToFind)) {
          return data[codeToFind];
        }

        // 遍历当前层级的子项进行递归搜索
        for (let key in data) {
          if (data[key].hasOwnProperty('sub')) {
            const found = search(codeToFind, data[key].sub);
            if (found) {
              return found;
            }
          }
        }

        // 如果当前层级及子层级都没有找到匹配，返回null
        return null;
      }

      return search(code, jsonData);
    },
    /**
     *
     * @param {Object} obj 地图区域数据
     * @param {String} name 区域名称
     * @param {Number} code 区域编码
     * @retrun {Object} 区域子集下的区域数据
     */
    rewindData(obj, name = '中国', code='china', per) {
      let dataList = []
      for (let k in obj) {
        dataList.push({
          value: obj[k].num,
          name: obj[k].name,
          regionCode: k
        })
      }
      const data = {
        dataList,
        regionCode: code,
        name,
        per
      }
      console.log(data)
      return data
    }
  }
}
</script>
<style lang="scss" scoped>
.centermap {
  margin-bottom: 30px;

  .maptitle {
    height: 60px;
    display: flex;
    justify-content: center;
    padding-top: 10px;
    box-sizing: border-box;

    .titletext {
      font-size: 28px;
      font-weight: 900;
      letter-spacing: 6px;
      // background: linear-gradient(
      //   92deg,
      //   #0072ff 0%,
      //   #00eaff 48.8525390625%,
      //   #01aaff 100%
      // );
      background: linear-gradient(92deg, #058b96 0%, #56b9c2 48.8525390625%, #43c5d1 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      margin: 0 10px;
    }

    .zuo,
    .you {
      background-size: 100% 100%;
      width: 29px;
      height: 20px;
      margin-top: 8px;
    }

    .zuo {
      background: url("../../assets/img/xiezuo.png") no-repeat;
    }

    .you {
      background: url("../../assets/img/xieyou.png") no-repeat;
    }
  }

  .mapwrap {
    height: 548px;
    width: 100%;
    // padding: 0 0 10px 0;
    box-sizing: border-box;
    position: relative;

    .quanguo {
      position: absolute;
      right: 20px;
      top: -46px;
      width: 80px;
      height: 28px;
      border: 1px solid #00eded;
      border-radius: 10px;
      color: #00f7f6;
      text-align: center;
      line-height: 26px;
      letter-spacing: 6px;
      cursor: pointer;
      box-shadow: 0 2px 4px rgba(0, 237, 237, 0.5),
        0 0 6px rgba(0, 237, 237, 0.4);
    }
  }
}
</style>
